#include "kernel/types.h"
#include "kernel/stat.h"
#include "user/user.h"
#include "kernel/fs.h"

void
find(char *path, char *path1)
{
  char buf[512], *p;
  int fd;
  struct dirent de;
  struct stat st;

  if((fd = open(path, 0)) < 0){
    fprintf(2, "cannot find in %s\n", path);
    return;
  }

  if(fstat(fd, &st) < 0){
    fprintf(2, "cannot stat %s\n", path);
    close(fd);
    return;
  }

  switch(st.type){
  case T_FILE:
    fprintf(2, "cannot find in %s\n", path);
    return;

  case T_DIR:
    if(strlen(path) + 1 + DIRSIZ + 1 > sizeof buf){
      printf("ls: path too long\n");
      break;
    }
    strcpy(buf, path);
    p = buf+strlen(buf);
    *p++ = '/';
    while(read(fd, &de, sizeof(de)) == sizeof(de)){
      if(de.inum == 0)
        continue;
      memmove(p, de.name, DIRSIZ);
      p[DIRSIZ] = 0; // 强制加截断符，防止文件名过长出错
      if(stat(buf, &st) < 0){
        printf("cannot stat %s\n", buf);
        continue;
      }
      if(st.type == T_FILE && strcmp(path1, p) == 0) {
            printf("%s\n", buf);
      } else if(st.type == T_DIR && strcmp(p, ".") != 0 && strcmp(p, "..") != 0){
        find(buf, path1);
      }
    }
    break;
  }
  close(fd);
}

int
main(int argc, char *argv[])
{
    if(argc != 3) {
        printf("usage:find [path] [file/path]");
    }
    find(argv[1], argv[2]);
    exit(0);
}

